﻿/* 
 * Since 2008 - 2012
 */

package com.hh.bss.project.service.impl;

import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;

import com.hh.bss.auth.client.OnlineUser;
import com.hh.bss.auth.entity.SystemBranchCompany;
import com.hh.bss.auth.entity.SystemUser;
import com.hh.bss.auth.service.SystemBranchCompanyService;
import com.hh.bss.base.*;
import com.hh.bss.common.ConstantDic;
import com.hh.bss.common.MapObjectRowMapper;
import com.hh.bss.common.SystemConstant;
import com.hh.bss.common.cache.SystemDicCache;
import com.hh.bss.common.cache.SystemUserCache;
import com.hh.bss.common.page.*;
import com.hh.bss.common.page.impl.*;
import com.hh.bss.config.Environment;
import com.hh.bss.customer.entity.Company;
import com.hh.bss.customer.service.CompanyService;
import com.hh.bss.customer.service.CustomerService;
import com.hh.bss.project.dao.*;
import com.hh.bss.project.entity.*;
import com.hh.bss.project.service.*;
import com.hh.bss.project.vo.query.*;
import com.hh.bss.sysadmin.entity.SystemTemplate;
import com.hh.bss.sysadmin.service.SystemTemplateService;
import com.hh.bss.talent.entity.Cv;
import com.hh.bss.talent.service.CvService;
import com.hh.bss.util.*;



import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;


@Service
@Transactional
public class AccountPnServiceImpl extends BaseBusinessService<AccountPn,java.lang.Integer>  implements AccountPnService<AccountPn,java.lang.Integer>{

	private AccountPnDao accountPnDao;
	private CvService cvService;
	private CompanyService companyService;
	private SystemTemplateService systemTemplateService;
	private SystemBranchCompanyService systemBranchCompanyService;
	/**增加setXXXX()方法,spring就可以通过autowire自动设置对象属性,请注意大小写*/
	public void setAccountPnDaoImpl(AccountPnDao dao) {
		this.accountPnDao = dao;
	}
	public EntityDao getEntityDao() {
		return this.accountPnDao;
	}
	public void setCompanyServiceImpl(CompanyService service) {
		this.companyService = service;
	}	
	public void setSystemTemplateServiceImpl(SystemTemplateService service) {
		this.systemTemplateService = service;
	}	
	public void setSystemBranchCompanyServiceImpl(SystemBranchCompanyService service) {
		this.systemBranchCompanyService = service;
	}
	
	public void setCvServiceImpl(CvService service) {
		this.cvService = service;
	}	
	
	@Transactional(readOnly=true)
	public Page findPage(AccountPnQuery query) {
		return accountPnDao.findPage(query);
	}
	
//	@Transactional(readOnly=true)
//	public AccountPn getByNbr(java.lang.String v) {
//		return accountPnDao.getByNbr(v);
//	}	
	public void save(AccountPn accountPn) throws DataAccessException{
		//检查是否有推荐过
		
		//检查当前账单状态，如果是“取消”的，不限制第二张账单的建立，如果是“已发邮件”的，保护期为三个月，账单超过三个月，无论何种状态，允许新增账单
		
		Object[] osnbr={accountPn.getNbr()};
		List lnbr=accountPnDao.getHibernateTemplate().find("from AccountPn t where t.nbr=?",osnbr);
		if(lnbr!=null&&lnbr.size()>0)  throw new RuntimeException("Offer存在编号相同的账单["+accountPn.getNbr()+"]，不能添加");
		Object[] os={accountPn.getOfferId()};
		List l=accountPnDao.getHibernateTemplate().find("from AccountPn t where t.offerId=?",os);
		if(l!=null&&l.size()>0) {
			boolean allowAdd=true;
			AccountPn oldAccountPn=null;
			for(int i=0;i<l.size();i++){
				oldAccountPn=(AccountPn)l.get(i);
				
				if (oldAccountPn.getStatus()!=null&&ConstantDic.AccountPnStatus_Cancel.equals(oldAccountPn.getStatus().toString())) continue;
				Date pd=DateHelper.add(oldAccountPn.getCreateDt(), DateHelper.DAY, 90);				
				if (pd.after(new Date())) allowAdd=false;
			}
			if (!allowAdd)
			throw new RuntimeException("Offer已经添加过账单，不能重复添加");
		}
		accountPnDao.save(accountPn);
	}
	
	public void saveFile(MultipartHttpServletRequest multipartRequest,
			MultipartFile multipartFile, AccountPn accountPn) {
		// TODO Auto-generated method stub
		SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMdd");     
		  
		//把公司id也加到目录里
	       String fileWebPathDir = Environment.UPLOADFILEDIR+"/"+SystemConstant.PN+"/"+dateformat.format(new Date())+"/"+accountPn.getOfferId();      
	       /**得到文件保存目录的真实路径**/     
	       String fileRealPathDir = multipartRequest.getSession().getServletContext().getRealPath(fileWebPathDir);     
	       /**根据真实路径创建目录**/     
	       File fileSaveDir = new File(fileRealPathDir);     
	       if(!fileSaveDir.exists()) {    
	           fileSaveDir.mkdirs();     
	       }   
	       /**页面控件的文件流**/     
	       //MultipartFile multipartFile = multipartRequest.getFile("fileRes");      			       			      			       
	       /**上传文件名称**/     
	       String uploadFileName = multipartFile.getOriginalFilename();//    
	         
	       
	       /**获取文件的后缀**/     
	       String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".")+1);     
	       String preName = multipartFile.getOriginalFilename().substring(0,multipartFile.getOriginalFilename().indexOf("."));
	       // 文件类型   
	         
	       // 获取文件大小，以kB为单位   
	       long size = multipartFile.getSize();   
	       Double fSize =Math.round(size/1024.0*100)/100.0;   
	       String fileSize = Double.toString(fSize)+"KB";
	       if (fSize==0) fSize=new Double(1);
	       /**拼成完整的文件保存路径加文件**/  
	       //重新命名
	       if(!StringHelper.isEmpty(suffix))uploadFileName=RandomStringUtil.getString(8)+"."+suffix;
	       else uploadFileName=RandomStringUtil.getString(8);
	       String fileName = fileRealPathDir + File.separator   + uploadFileName;     
	       
	       File file = new File(fileName);      
	          
	       try {     
	           multipartFile.transferTo(file);  //将文件写入到指定的目录   
	       } catch (IllegalStateException e) {     
	           e.printStackTrace();     
	       } catch (IOException e) {            
	           e.printStackTrace();     
	       }    
	      
	       accountPn.setUploadDoc(fileWebPathDir+"/"+ uploadFileName);
	}
	
	public File genPnFile(HttpServletRequest request,OnlineUser onlineUser,AccountPn accountPn) {
		// TODO Auto-generated method stub
		//取
		StringBuffer sql = new StringBuffer();
	    List values = new ArrayList();
	    sql.append(" select * from ( "); //checkinDString
	    sql.append(" select a.create_dt createDt,a.nbr,a.final_ar finalAr,a.currency,a.branch_nbr branchNbr,c.cv_id cvId,d.name jobName,d.job_manager jobManager,b.apply_d applyD,b.onduty_d ondutyD,b.checkin_d checkinD,d.work_location workLocation,d.cust_id custId from account_pn a,contract_job_cv_offer b,contract_job_cv_recom c,contract_job d where a.id=? and a.offer_id=b.id and b.recom_id=c.id and c.job_id=d.id ");
	    sql.append(" ) t ");
	    values.add(accountPn.getId());
	    List l=accountPnDao.getJdbcDao().findByQuery(sql.toString(), values.toArray(), new MapObjectRowMapper());
	    Map dataMap=new HashMap();
	    //if (onlineUser!=null) dataMap.put("signer",onlineUser.getName());
	    //accountPn.getSender()
	    SystemUser user=SystemUserCache.getSystemUserByUsername(accountPn.getSender());
	    if (user!=null) dataMap.put("signer",user.getName());
	    //if ()
	    //OnlineManager onlineManager=super.getOnlineManager(request, null);
	    
	    if (l!=null&&l.size()>0){
	    	Map m=(Map)l.get(0);
	    	
	    	//取客户
		    Company company=companyService.getByCustId((Integer)m.get("custId"));
		    dataMap.put("createDt", m.get("createDt"));
		    dataMap.put("pnNbr", m.get("nbr"));
		    if (company!=null){
		    	dataMap.put("custName", StringHelper.clearHTMLTag(company.getName()));
		    	dataMap.put("custAddress", StringHelper.clearHTMLTag(company.getAddress()));
		    	dataMap.put("custPostcode", StringHelper.clearHTMLTag(company.getPostcode()));
		    	dataMap.put("custTel", StringHelper.clearHTMLTag(company.getTel()));
		    	dataMap.put("custFax", StringHelper.clearHTMLTag(company.getFax()));
		    }
		  //取候选人
		    //System.out.println("sdfdsfds--------------:"+m);
		    Cv cv=cvService.getById((Integer)m.get("cvId"));
		    if (cv!=null){
		    	StringBuffer cvNameSb=new StringBuffer( cv.getCvName());
		    	
		    	if (!StringHelper.isEmpty(cv.getCvNameEn())){
		    		cvNameSb.append("(").append(cv.getCvNameEn()).append(")");
		    	}
		    	//if (cv.getCvNameEn())
		    	dataMap.put("cvNameCn", StringHelper.clearHTMLTag(cv.getCvName()));
		    	dataMap.put("cvName", StringHelper.clearHTMLTag(cvNameSb.toString()));
		    	
		    }
		    
		   //取公司账务信息
		    String nbr="";
		    SystemBranchCompany systemBranchCompany=null;
		    //优先使用账单里的收款公司设置 
		    if (!StringHelper.isEmpty(accountPn.getBranchNbr())){
		    	nbr=accountPn.getBranchNbr();
		    	systemBranchCompany=systemBranchCompanyService.getByNbr(nbr);
		    }else{
		    	//没有则使用操作用户所在公司
		    	SystemUser systemUser=SystemUserCache.getSystemUserByUsername(accountPn.getCreator());
		    	
		    	if (systemUser!=null){
		    		//nbr=systemUser.get
		    		if (systemUser.getBranchCompanyId()!=null&&systemUser.getBranchCompanyId().intValue()!=0)
		    			systemBranchCompany=(SystemBranchCompany) systemBranchCompanyService.getById(systemUser.getBranchCompanyId());
		    	}
		    }
		    if (systemBranchCompany!=null){
		    	dataMap.put("tbBank", StringHelper.clearHTMLTag(systemBranchCompany.getBank()));
		    	dataMap.put("tbBankAccountName", StringHelper.clearHTMLTag(systemBranchCompany.getAccountName()));
		    	dataMap.put("tbBankAccountNo", StringHelper.clearHTMLTag(systemBranchCompany.getAccountNo()));
		    }
		    //
		    
		    dataMap.put("jobName", StringHelper.clearHTMLTag((String)m.get("jobName")));
		    dataMap.put("jobManager", StringHelper.clearHTMLTag((String)m.get("jobManager")));
		    dataMap.put("applyD", m.get("applyD"));
		    dataMap.put("ondutyD", m.get("checkinD"));  //预估上班日期 改成 时间上班日期 alvin 2013年2月28日17:22:53
		    dataMap.put("finalAr", m.get("finalAr"));
		    dataMap.put("currency", m.get("currency"));
		    		    
		    dataMap.put("workLocation", SystemDicCache.getCodeName("LOCATION", ObjectUtils.toString(m.get("workLocation"))));
		    
	    }
	   // dataMap=new HashMap();
	    
		
	  //开始生成
		Configuration configuration = new Configuration();
		configuration.setDefaultEncoding("utf-8");
		//configuration.setServletContextForTemplateLoading(request.getSession().getServletContext(), "");
		configuration.setClassForTemplateLoading(this.getClass(), "/template");
		configuration.setClassicCompatible(true);
		configuration.setDateFormat("yyyy-MM-dd");
		configuration.setDateTimeFormat("yyyy-MM-dd");
		//
		//取模板
		String templateType=ConstantDic.PnTemplate_PNT6;
		if (!StringHelper.isEmpty(accountPn.getTemplateType())) templateType=accountPn.getTemplateType();
		SystemTemplate systemTemplate=systemTemplateService.getSystemTemplateByType(templateType);
		
		Template t=null;
		try {			
			
			StringBuffer str=FileHelper.read(this.getClass().getResource(systemTemplate.getFile()).getPath(),"UTF-8");
			
			//String templateText= str.toString().replaceAll("<!---", "").replaceAll("--->", "");
			String templateText= str.toString();
			
			StringTemplateLoader stringTemplateLoader=new StringTemplateLoader();
			stringTemplateLoader.putTemplate("template", templateText);
			//test.ftl为要装载的模板
			configuration.setTemplateLoader(stringTemplateLoader);
			t = configuration.getTemplate("template");
			
			//configuration.s
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		//输出文档路径及名称
		 SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMdd");  
		 String fileWebPathDir = Environment.UPLOADFILEDIR+"/"+SystemConstant.PN+"/"+dateformat.format(new Date());//+"/"+accountPn.getCvId();      
         /**得到文件保存目录的真实路径**/     
         String fileRealPathDir = request.getSession().getServletContext().getRealPath(fileWebPathDir);     
         /**根据真实路径创建目录**/     
         File fileSaveDir = new File(fileRealPathDir);
         //fileSaveDir.i
         if(!fileSaveDir.exists()) {    
            fileSaveDir.mkdirs();     
         }   
		String fileName="PN_"+accountPn.getId()+".doc";
		accountPn.setUploadDoc(fileWebPathDir+"/"+ fileName);
		File outFile = new File(request.getSession().getServletContext().getRealPath(fileWebPathDir+"/"+fileName));
		
		Writer out = null;
		try {
			
			out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"utf-8"));
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 
        try {
        	//System.out.println(t.toString());
        	
			t.process(dataMap, out);
		} catch (TemplateException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			
			e.printStackTrace();
			return null;
		}finally{
			if (out!=null)
				try {
					out.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
		
		
		
		return outFile;
	}
	@Override
	public List findAccountPnListByNbr(String nbr) {
		// TODO Auto-generated method stub
		return this.accountPnDao.findAccountPnListByNbr(nbr);
	}
	
}
